﻿// 角色管理ExtJs
function Infra_Role() {
    // 定义继承于的角色store
    var InheritRoleStore = new Ext.data.JsonStore({
        url: '/InfraHospUser/GetRoleQueryList',
        root: 'data',
        totalProperty: 'total',
        id: 'Id',
        fields: [{
            name: 'Id',
            type: 'string'
        }, {
            name: 'Name',
            type: 'string'
        }, {
            name: 'Code',
            type: 'string'
        }]
    });

    // 定义表格用角色store
    var itemGridStore = new Ext.data.Store({
        url: "/InfraRole/GetPlist",
        remoteSort: true,
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'total',
            id: 'Id'
        }, [{
            name: 'Id',
            type: 'string'// ID
        }, {
            name: 'Name', // 名称
            type: 'string'
        }, {
            name: 'State', // 状态
            type: 'string'
        }, {
            name: 'Code', // 代码
            type: 'string'
        }]),
        listeners: {
            'remove': function (thiz, record, index) {
                MenuStore.removeAll();
                ActionPermissionitemGridStore.removeAll();
                ActionPermissionPanelInitFlag = false;
                MenuPermissionPanelInitFlag = false;
                UserPermissionPanelInitFlag = false;
            }
        }
    });
    itemGridStore.setDefaultSort('Name', 'ASC'); // 设置默认排序

    // 定义filters
    var filters = new Ext.ux.grid.GridFilters({
        encode: true,
        filters: [{
            type: 'string',
            dataIndex: 'Id'
        }, {
            type: 'string',
            dataIndex: 'Name'
        }, {
            type: 'string',
            dataIndex: 'Code'
        }]
    });
    var menuRecord = Ext.data.Record.create([{
        name: 'Name'
    }, {
        name: 'TreeCode'
    }, {
        name: 'Id',
        type: 'string'
    }, {
        name: 'ParentId',
        type: 'auto'
    }, {
        name: 'Leaf',
        type: 'bool'
    }, {
        name: 'Level',
        type: 'int'
    }, {
        name: 'ActionName',
        type: 'string'
    }, {
        name: 'ControllerName',
        type: 'string'
    }, {
        name: 'Index',
        type: 'int'
    }, {
        name: 'Description',
        type: 'string'
    }, {
        name: 'URL',
        type: 'string'
    }, {
        name: 'BigIcon',
        type: 'string'
    }, {
        name: 'SmallIcon',
        type: 'string'
    }, {
        name: 'IsExtPage',
        type: 'bool'
    }, {
        type: 'date',
        name: 'CreateTime'
    }]);
    var MenuStore = new Ext.ux.maximgb.tg.AdjacencyListStore({
        reader: new Ext.data.JsonReader({
            id: 'Id',
            root: 'data'
        }, menuRecord),
        url: '/InfraRole/GetMenuGrid'
    });
    MenuStore.setDefaultSort('Index', 'ASC');

    var MenuRootReocdData = {
        "Name": "所有菜单",
        "Code": "",
        "Id": "0",
        "ParentId": null,
        "Leaf": null,
        "Level": 0,
        "IsExtPage": null
    };
    MenuStore.isLoadedNode = function (rc) {
        return true;
    }
    var menuRootReocd = new MenuStore.recordType(MenuRootReocdData, 0);
    var ActionPermissionPanelInitFlag = false;
    var UserPermissionPanelInitFlag = false;
    var MenuPermissionPanelInitFlag = false;
    var RoleStoreUpdataFlag = false;
    // 定义表格选择方式
    var RoleSM = new Ext.grid.CheckboxSelectionModel({
        singleSelect: true,
        listeners: {
            'rowselect': function (sm, rowIndex, r) {
                if (RoleStoreUpdataFlag) {
                    RoleStoreUpdataFlag = false;
                    return;
                }
                var id = sm.getSelected().get("Id");
                if (PermissionTab.getActiveTab().getId() == "Infra_Role_PermissionTab_MenuPermissionPanel") {
                    MenuStore.removeAll();
                    MenuStore.insert(0, menuRootReocd);
                    MenuStore.load({
                        add: true
                    });
                    MenuPermissionPanelInitFlag = true;
                } else if (PermissionTab.getActiveTab().getId() == "Infra_Role_PermissionTab_ActionPermissionPanel") {
                    ActionPermissionitemGridStore.removeAll();
                    ActionPermissionitemGridStore.baseParams["Id"] = sm
							.getSelected().get("Id");
                    ActionPermissionitemGridStore.load({
                        params: {
                            start: 0,
                            limit: ALL_PAGESIZE_SETTING
                        }
                    });
                    ActionPermissionPanelInitFlag = true;
                } else if (PermissionTab.getActiveTab().getId() == "Infra_Role_PermissionTab_UserPermissionPanel") {
                    gridStoreUser.removeAll();
                    gridStoreUser.baseParams["rolecode"] = RoleSM.getSelected().get("Code");
                    gridStoreUser.load({
                        params: {
                            start: 0,
                            limit: ALL_PAGESIZE_SETTING
                        }
                    });
                    UserPermissionPanelInitFlag = true;
                }
            },
            'rowdeselect': function (sm, rowIndex, r) {
                MenuStore.removeAll();
                ActionPermissionitemGridStore.removeAll();
                ActionPermissionPanelInitFlag = false;
                MenuPermissionPanelInitFlag = false;
                UserPermissionPanelInitFlag = false;
            }
        }
    });
    // 定义表格列
    var cm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), RoleSM, {
        header: "代码",
        dataIndex: 'Code',
        sortable: true
    }, {
        header: "角色名称",
        dataIndex: 'Name',
        sortable: true,
        width: 150
    }, {
        header: "状态",
        dataIndex: 'State',
        sortable: true,
        renderer: function (v) {
            return v == null ? "" : (StateStore.getById(v)).get("Key");
        }
    }]);
    // 定义表单用角色Reader
    var RoleEditFormReader = new Ext.data.JsonReader({
        root: 'data'
    }, [{
        name: 'Name', // 角色名称
        type: 'string'
    }, {
        name: 'Code', // 角色编码
        type: 'string'
    }, {
        name: 'State', // 角色状态
        type: 'string'
    }, {
        name: 'Description', // 描述
        type: 'string'
    }]);
    // 角色编辑窗口
    var showRoleEditFormWinFn = function (formReader, title, id) {
        // 定义变量 是否更新操作标记 更新：true 添加：false
        var updateEdit = Ext.isDefined(id);
        // 定义表单验证成功后的提交参数及返回处理
        var formSubmitArgs = {
            url: '/InfraRole/SaveOrUpdate',
            params: {
                'Id': (updateEdit) ? id : ""
            },
            success: function (form, action) {
                if (!updateEdit) {
                    itemGridStore.setDefaultSort('CreateTime', 'DESC');
                    RoleSM.clearSelections();
                    itemGridStore.load({// 刷新表格
                        params: {
                            start: 0,
                            limit: ALL_PAGESIZE_SETTING
                        }
                    });
                } else {
                    RoleStoreUpdataFlag = true;
                    itemGridStore.reload();
                }
                win.destroy(); // 关闭窗口
            },
            failure: function (form, action) {
                JsHelper.ShowError(action.result.msg);
            }
        };
        // 定义获得表单初始加载数据的请求参数
        var formLoadArgs = (updateEdit) ? {
            url: '/InfraRole/GetRole',
            params: {
                'Id': id
            },
            waitMsg: '数据加载中...'
        } : null;
        // 定义表单第一列的组件对象集合 默认xtype为textfield
        var firstColumn = [{
            fieldLabel: '角色名称<span style="color: red;" >*</span>',
            allowBlank: false,
            width: 150,
            name: 'Name',
            disabled: updateEdit,
            rvOptions: {
                url: '/InfraRole/IsFieldExist',
                params: {
                    'Id': "-1",
                    'FieldName': 'Name'
                }
            },
            plugins: [Ext.ux.plugins.RemoteValidator]
        }, {
            fieldLabel: '角色状态<span style="color: red;" >*</span>',
            width: 150,
            allowBlank: false,
            xtype: 'basecombo',
            name: 'State',
            hiddenName: 'State',
            store: StateStore,
            valueField: 'Value',
            displayField: 'Key'
        }];
        // 定义表单第二列的组件对象集合
        var secondColumn = [{
            fieldLabel: '编码<span style="color: red;" >*</span>',
            allowBlank: false,
            disabled: updateEdit,
            width: 150,
            name: 'Code',
            rvOptions: {
                url: '/InfraRole/IsFieldExist',
                params: {
                    'Id': "-1",
                    'FieldName': 'Code'
                }
            },
            plugins: [Ext.ux.plugins.RemoteValidator]
        }, {
            fieldLabel: '继承于',
            xtype: 'sicombo',
            store: InheritRoleStore,
            hiddenName: 'InheritRole.Id',
            valueField: 'Id',
            displayField: 'Name',
            emptyText: "请选择...",
            listWidth: 280,
            hideLabel: updateEdit,
            disabled: updateEdit,
            hidden: updateEdit,
            tpl: new Ext.XTemplate(
							'<div class="x-grid3"><div><table>',
							'<thead class="x-grid3-header"><tr class="x-grid3-hd-row">',
							'<td class="x-grid3-hd x-grid3-cell x-grid3-hd-inner" style="width: 80px;color: blue;">编码</td>',
							'<td class="x-grid3-hd x-grid3-cell" style="width: 200px;color: blue;">名称</td>',
							'</tr></thead><tbody>',
							'<tpl for=".">',
							'<tr class="x-combo-list-item">',
							'<td class="x-grid3-col x-grid3-cell"><div class="x-grid3-cell-inner"  style="font-size:12px;">{Code}</div></td>',
							'<td class="x-grid3-col x-grid3-cell"><div class="x-grid3-cell-inner"  style="font-size:12px;">{Name}</div></td>',
							'</tr>', '</tpl>', '</tbody></table></div></div>')
        }];
        // 定义表单单独列的组件对象集合
        var singleColumn = [{
            xtype: 'textarea',
            fieldLabel: '描述',
            name: 'Description',
            height: 50,
            width: 430
        }];
        // 定义表单 头部固定为两列 末尾单独列
        var form = new Ext.FormPanel({
            border: false,
            waitMsgTarget: true,
            labelWidth: 90,
            frame: true,
            bodyStyle: 'padding:5px 5px 0',
            reader: formReader,
            labelAlign: 'right',
            items: [{
                layout: 'column',
                items: [{
                    columnWidth: .5,
                    bodyStyle: 'padding:1px',
                    layout: 'form',
                    defaultType: 'textfield',
                    defaults: {
                        width: 150
                    },
                    items: firstColumn
                }, {
                    columnWidth: .5,
                    bodyStyle: 'padding:1px',
                    layout: 'form',
                    defaultType: 'textfield',
                    defaults: {
                        width: 150
                    },
                    items: secondColumn
                }]
            }, singleColumn],
            buttonAlign: 'center',
            buttons: [new Ext.ux.SubmitBtn({
                handler: function () {
                    if (form.getForm().isValid()) {
                        form.getForm()
														.submit(formSubmitArgs); // formSubmitArgs
                        // 引用之前定义的请求参数变量
                    }
                }
            }), new Ext.ux.CancelBtn({
                handler: function () {
                    win.destroy();
                }
            })]
        });
        // 定义显示窗口
        var win = new Ext.Window({
            title: title,
            iconCls: 'application_form',
            width: 600,
            resizable: false,
            constrain: true,
            autoHeight: true,
            modal: true,
            closeAction: 'close',
            plain: true,
            items: [form]
        });
        win.show();
        if (formLoadArgs) {
            form.load(formLoadArgs);
        }
    };
    // 定义表格工具栏
    var tbar = [{
        xtype: "tbbutton",
        minWidth: 80,
        ref: '../addBtn',
        text: "添加角色",
        cls: "x-btn-text-icon",
        icon: "/Content/icons/add.png",
        handler: function (btn, e) {
            showRoleEditFormWinFn(RoleEditFormReader, "添加角色");
        }
    }, "-", {
        xtype: "tbbutton",
        ref: '../delBtn',
        minWidth: 80,
        disabled: true,
        text: "删除角色",
        cls: "x-btn-text-icon",
        icon: "/Content/icons/delete.png",
        handler: function (btn, e) {
            JsHelper.DelConfirm(function (btn) {
                if (btn == 'yes') {
                    var records = grid.getSelectionModel()
										.getSelections();
                    for (var i = 0; i < records.length; i++) {
                        Ext.Ajax.request({
                            url: '/InfraRole/Delete',
                            params: {
                                'Id': records[i].get("Id")
                            },
                            success: function (response, opts) {
                                var result = Ext.util.JSON
													.decode(response.responseText);
                                if (result.success == false) {
                                    JsHelper.ShowError(result.msg);
                                } else {
                                    var paramsId = opts.params.Id;
                                    var r = itemGridStore
														.getById(paramsId);
                                    if (Ext.isDefined(r)) {
                                        itemGridStore.remove(r);
                                    }
                                }
                            }
                        });
                    }
                }
            });
        }
    }, "-", {
        xtype: "tbbutton",
        minWidth: 80,
        text: "双击修改角色",
        cls: "x-btn-text-icon",
        icon: "/Content/icons/pencil.png",
        disabled: true
    }];

    // 分页工具栏
    var bbar = new Ext.PagingToolbar({
        displayInfo: true,
        emptyMsg: "没有数据显示",
        // displayMsg : "{0}到{1}条，共{2}条",
        displayMsg: "{0}到{1}条，共{2}条",
        store: itemGridStore,
        pageSize: ALL_PAGESIZE_SETTING,
        plugins: [filters]
    })
    // 角色维护表格
    var grid = new Ext.grid.GridPanel({
        region: "west",
        width: 350,
        enableColumnMove: false,
        sm: RoleSM,
        cm: cm,
        plugins: [filters],
        stripeRows: true,
        frame: true,
        border: true,
        viewConfig: {
            forceFit: true
        },
        store: itemGridStore,
        loadMask: true,
        tbar: tbar,
        bbar: bbar,
        listeners: {
            "rowdblclick": function (g, rowIndex, e) {
                var store = g.getStore()
                var id = store.getAt(rowIndex).get("Id");
                showRoleEditFormWinFn(RoleEditFormReader, "修改角色", id);
            }
        }
    });
    // 控制删除按钮
    grid.getSelectionModel().on('selectionchange', function (sm) {
        grid.delBtn.setDisabled(sm.getCount() < 1);
    });
    var menuSM = new Ext.grid.CheckboxSelectionModel({
        header: '',
        checkOnly: true,
        listeners: {
            'rowselect': function (sm, rowIndex, r) {
                var id = r.get("Id");
                var ids = [];
                var level = r.get("Level");
                if (level == 0) {
                    var records = MenuStore.getRange(1);
                    for (var i = 0; i < records.length; i++) {
                        if (!sm.isSelected(MenuStore.indexOf(records[i]))) {
                            ids.push(records[i].get("Id"));
                        }
                    }
                } else {
                    ids.push(r.get("Id"));
                    if (level == 1) {
                        var records = MenuStore.getNodeChildren(r);
                        for (var i = 0; i < records.length; i++) {
                            if (!sm.isSelected(MenuStore.indexOf(records[i]))) {
                                ids.push(records[i].get("Id"));
                            }
                        }
                    }
                    if (level == 2) {
                        var pRecord = MenuStore.getNodeParent(r);
                        var index = MenuStore.indexOf(pRecord);
                        if (!sm.isSelected(index)) {
                            ids.push(pRecord.get("Id"));
                        }
                    }
                }
                if (ids.length > 0) {
                    Ext.Ajax.request({
                        url: '/InfraRole/SaveMenu',
                        params: {
                            'MId': ids.toString(),
                            'Id': RoleSM.getSelected().get("Id")
                        },
                        success: function (response, opts) {
                            var result = Ext.util.JSON
											.decode(response.responseText);
                            if (result.success == false) {
                                JsHelper.ShowError(result.msg);
                            } else {
                                var paramsMId = opts.params.MId
												.split(",");
                                for (var i = 0; i < paramsMId.length; i++) {
                                    var index = MenuStore.find("Id",
													paramsMId[i]);
                                    var record = MenuStore.getAt(index);
                                    if (!menuSM.isSelected(index)) {
                                        menuSM.selections.add(record);
                                        menuGrid.getView()
														.onRowSelect(index);
                                    }
                                }
                            }
                        }
                    });
                }
            },
            'rowdeselect': function (sm, rowIndex, r) {
                var ids = [];
                var id = r.get("Id");
                var level = r.get("Level");
                if (level == 0) {
                    var records = MenuStore.getRange(1);
                    for (var i = 0; i < records.length; i++) {
                        if (sm.isSelected(MenuStore.indexOf(records[i]))) {
                            ids.push(records[i].get("Id"));
                        }
                    }
                } else {
                    ids.push(r.get("Id"));
                    if (level == 1) {
                        var records = MenuStore.getNodeChildren(r);
                        for (var i = 0; i < records.length; i++) {
                            if (sm.isSelected(MenuStore.indexOf(records[i]))) {
                                ids.push(records[i].get("Id"));
                            }
                        }
                    }
                    if (level == 2) {
                        var pRecord = MenuStore.getNodeParent(r);
                        var records = MenuStore.getNodeChildren(pRecord);
                        var pselectflag = false;
                        for (var i = 0; i < records.length; i++) {
                            pselectflag = sm.isSelected(MenuStore
									.indexOf(records[i]))
                            if (pselectflag) {
                                break;
                            }
                        }
                        if (!pselectflag) {
                            ids.push(pRecord.get("Id"));
                        }
                    }
                }
                Ext.Ajax.request({
                    url: '/InfraRole/DeleteMenu',
                    params: {
                        'MId': ids.toString(),
                        'Id': RoleSM.getSelected().get("Id")
                    },
                    success: function (response, opts) {
                        var result = Ext.util.JSON
										.decode(response.responseText);
                        if (result.success == false) {
                            JsHelper.ShowError(result.msg);
                        } else {
                            var paramsMId = opts.params.MId.split(",");
                            for (var i = 0; i < paramsMId.length; i++) {
                                var index = MenuStore.find("Id",
												paramsMId[i]);
                                var record = MenuStore.getAt(index);
                                if (menuSM.isSelected(index)) {
                                    menuSM.selections.remove(record);
                                    menuGrid.getView()
													.onRowDeselect(index);
                                }
                            }
                        }
                    }
                });
            }
        }
    });
    var menuGrid = new Ext.ux.maximgb.tg.GridPanel({
        enableColumnMove: false,
        frame: true,
        border: true,
        sm: menuSM,
        layout: "fit",
        loadMask: true,
        store: MenuStore,
        master_column_id: 'Name',
        columns: [menuSM, {
            id: 'Name',
            header: "菜单名",
            width: 160,
            dataIndex: 'Name'
        }, {
            header: "代码",
            width: 70,
            dataIndex: 'TreeCode'
        }, {
            header: "Controller名称",
            dataIndex: 'ControllerName'
        }, {
            header: "Action名称",
            dataIndex: 'ActionName'
        }, {
            header: "排序",
            dataIndex: 'Index',
            width: 60
        }, {
            header: "描述",
            dataIndex: 'Description'
        }, {
            header: "大图标",
            dataIndex: 'BigIcon'
        }, {
            header: "小图标",
            dataIndex: 'SmallIcon'
        }, {
            header: "URL",
            dataIndex: 'URL'
        }, {
            header: "是否叶子菜单",
            dataIndex: 'Leaf',
            renderer: function (v) {
                if (v == null) {
                    return "";
                }
                if (v) {
                    return "是";
                } else {
                    return "否";
                }
            }
        }, {
            header: "是否EXT界面",
            dataIndex: 'IsExtPage',
            renderer: function (v) {
                if (v == null) {
                    return "";
                }
                if (v) {
                    return "是";
                } else {
                    return "否";
                }
            }
        }, {
            xtype: 'datecolumn',
            format: 'Y年m月d日 H:i:s',
            header: "创建时间",
            width: 150,
            dataIndex: 'CreateTime'
        }],
        stripeRows: true
    });
    // 功能权限表格Store
    var ActionPermissionitemGridStore = new Ext.data.Store({
        url: "/InfraRole/GetPlistActionPermission",
        remoteSort: true,
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'total',
            id: 'Id'
        }, [{
            name: 'Id',
            type: 'string'
        }, {
            name: 'ControllerName',
            type: 'string'
        }, {
            name: 'ActionName',
            type: 'string'
        }, {
            name: 'Description',
            type: 'string'
        }, {
            name: 'CreateTime',
            type: 'date'
        }])
    });
    ActionPermissionitemGridStore.setDefaultSort('ControllerName', 'ASC');
    // 功能权限filters
    var ActionPermissionitemGridFilters = new Ext.ux.grid.GridFilters({
        encode: true,
        filters: [{
            type: 'string',
            dataIndex: 'ControllerName'
        }, {
            type: 'string',
            dataIndex: 'ActionName'
        }, {
            type: 'string',
            dataIndex: 'Description'
        }, {
            type: 'date',
            dataIndex: 'CreateTime'
        }]
    });
    var ActionPermissionsm = new Ext.grid.CheckboxSelectionModel({
        checkOnly: true,
        listeners: {
            'rowselect': function (sm, rowIndex, r) {
                var id = r.get("Id");
                Ext.Ajax.request({
                    url: '/InfraRole/SaveActionPermissions',
                    params: {
                        'PId': id,
                        'Id': RoleSM.getSelected().get("Id")
                    },
                    success: function (response, opts) {
                        var result = Ext.util.JSON
												.decode(response.responseText);
                        if (result.success == false) {
                            JsHelper.ShowError(result.msg);
                        }
                    }
                });
            },
            'rowdeselect': function (sm, rowIndex, r) {
                var id = r.get("Id");
                Ext.Ajax.request({
                    url: '/InfraRole/DeleteActionPermissions',
                    params: {
                        'PId': id,
                        'Id': RoleSM.getSelected().get("Id")
                    },
                    success: function (response, opts) {
                        var result = Ext.util.JSON
												.decode(response.responseText);
                        if (result.success == false) {
                            JsHelper.ShowError(result.msg);
                        }
                    }
                });
            }
        }
    });
    ActionPermissionsm.onHdMouseDown = function (e, t) {
        if (t.className == 'x-grid3-hd-checker') {
            e.stopEvent();
            var hd = Ext.fly(t.parentNode);
            var isChecked = hd.hasClass('x-grid3-hd-checker-on');
            var ids = [];
            var url = "";
            var records = ActionPermissionitemGridStore.getRange();
            if (isChecked) {
                hd.removeClass('x-grid3-hd-checker-on');
                url = "/InfraRole/DeleteOfActionPermissions";
                for (var i = 0; i < records.length; i++) {
                    if (this.isSelected(ActionPermissionitemGridStore
							.indexOf(records[i]))) {
                        ids.push(records[i].get("Id"));
                    }
                }
            } else {
                hd.addClass('x-grid3-hd-checker-on');
                url = "/InfraRole/SaveOfActionPermissions";
                for (var i = 0; i < records.length; i++) {
                    if (!this.isSelected(ActionPermissionitemGridStore
							.indexOf(records[i]))) {
                        ids.push(records[i].get("Id"));
                    }
                }
            }
            if (ids.length > 0) {
                Ext.Ajax.request({
                    url: url,
                    params: {
                        'PId': ids.toString(),
                        'Id': RoleSM.getSelected().get("Id")
                    },
                    success: function (response, opts) {
                        var result = Ext.util.JSON
								.decode(response.responseText);
                        if (result.success == false) {
                            JsHelper.ShowError(result.msg);
                        } else {
                            var url = opts.url;
                            var paramsPId = opts.params.PId.split(",");
                            for (var i = 0; i < paramsPId.length; i++) {
                                var index = ActionPermissionitemGridStore.find(
										"Id", paramsPId[i]);
                                var record = ActionPermissionitemGridStore
										.getAt(index);
                                if (url == "/InfraRole/SaveOfActionPermissions") {
                                    if (!ActionPermissionsm.isSelected(index)) {
                                        ActionPermissionsm.selections
												.add(record);
                                        ActionPermissionGrid.getView()
												.onRowSelect(index);
                                    }
                                } else if (url == "/InfraRole/DeleteOfActionPermissions") {
                                    if (ActionPermissionsm.isSelected(index)) {
                                        ActionPermissionsm.selections
												.remove(record);
                                        ActionPermissionGrid.getView()
												.onRowDeselect(index);
                                    }
                                }
                            }
                        }
                    }
                });
            }
        }
    }
    var ActionPermissioncm = new Ext.grid.ColumnModel([
			new Ext.grid.RowNumberer(), ActionPermissionsm, {
			    header: "Action名称",
			    dataIndex: 'ActionName',
			    sortable: true,
			    width: 200
			}, {
			    header: "Controller名称",
			    dataIndex: 'ControllerName',
			    sortable: true,
			    width: 200
			}, {
			    header: "描述",
			    dataIndex: 'Description',
			    sortable: true,
			    width: 200
			}, {
			    xtype: 'datecolumn',
			    format: 'Y年m月d日 H:i:s',
			    header: "创建时间",
			    sortable: true,
			    dataIndex: 'CreateTime',
			    width: 150
			}]);
    // 功能权限分页工具栏
    var ActionPermissionbbar = new Ext.PagingToolbar({
        displayInfo: true,
        emptyMsg: "没有数据显示",
        displayMsg: "{0}到{1}条，共{2}条",
        store: ActionPermissionitemGridStore,
        pageSize: ALL_PAGESIZE_SETTING,
        plugins: [filters]
    })
    // 功能权限维护表格
    var ActionPermissionGrid = new Ext.grid.GridPanel({
        region: "center",
        enableColumnMove: false,
        sm: ActionPermissionsm,
        cm: ActionPermissioncm,
        plugins: [ActionPermissionitemGridFilters],
        stripeRows: true,
        frame: true,
        border: true,
        layout: "fit",
        store: ActionPermissionitemGridStore,
        loadMask: true,
        bbar: ActionPermissionbbar
    });

    // 角色用户Store
    var gridStoreUser = Infrastructure.UserRoleDept.UserRoleDeptStore();
    gridStoreUser.setDefaultSort('Person.Code', 'ASC');
    // 角色用户Grid
    var UserRoleDeptGrid = Infrastructure.UserRoleDept.UserRoleDeptGrid();

    // 权限管理Tab页
    var PermissionTab = new Ext.TabPanel({
        id: "Infra_Role_PermissionTab",
        frame: true,
        border: true,
        region: "center",
        autoScroll: true,
        enableTabScroll: true,
        activeTab: 0,
        items: [new Ext.Panel({
            id: 'Infra_Role_PermissionTab_MenuPermissionPanel',
            title: '菜单权限',
            autoScroll: true,
            layout: 'fit',
            border: false,
            items: [menuGrid],
            listeners: {
                'activate': function (p) {
                    if (!MenuPermissionPanelInitFlag) {
                        MenuPermissionPanelInitFlag = true;
                        if (grid.getSelectionModel()
												.getSelected()) {
                            MenuStore.removeAll();
                            MenuStore.insert(0, menuRootReocd);
                            MenuStore.load({
                                add: true
                            });
                        }
                    }
                }
            }
        }), new Ext.Panel({
            id: 'Infra_Role_PermissionTab_ActionPermissionPanel',
            title: '功能权限',
            autoScroll: true,
            layout: 'fit',
            border: false,
            items: [ActionPermissionGrid],
            listeners: {
                'activate': function (p) {
                    if (!ActionPermissionPanelInitFlag) {
                        ActionPermissionPanelInitFlag = true;
                        if (grid.getSelectionModel().getSelected()) {
                            ActionPermissionitemGridStore.removeAll();
                            gridStoreUser.baseParams["Id"] = RoleSM.getSelected().get("Id");
                            ActionPermissionitemGridStore.load({
                                params: {
                                    start: 0,
                                    limit: ALL_PAGESIZE_SETTING
                                }
                            });
                        }
                    }
                }
            }
        }), new Ext.Panel({
            id: 'Infra_Role_PermissionTab_UserPermissionPanel',
            title: '授权用户',
            autoScroll: true,
            layout: 'fit',
            border: false,
            items: [UserRoleDeptGrid],
            listeners: {
                'activate': function (p) {
                    if (!ActionPermissionPanelInitFlag) {
                        ActionPermissionPanelInitFlag = true;
                        if (grid.getSelectionModel().getSelected()) {
                            gridStoreUser.removeAll();
                            gridStoreUser.baseParams["rolecode"] = RoleSM.getSelected().get("Code");
                            gridStoreUser.load({
                                params: {
                                    start: 0,
                                    limit: ALL_PAGESIZE_SETTING
                                }
                            });
                        }
                    }
                }
            }
        })]
    });
    MenuStore.on("load", function () {
        this.expandNode(menuRootReocd);
        Ext.Ajax.request({
            url: '/InfraRole/GetMenuListByRoleId',
            params: {
                'Id': RoleSM.getSelected().get("Id")
            },
            success: function (response, opts) {
                var result = Ext.util.JSON
										.decode(response.responseText);
                if (result.success == false) {
                    JsHelper.ShowError(result.msg);
                } else {
                    var idsData = result.data;
                    var len = idsData.length;
                    for (var i = 0; i < len; i++) {
                        var index = MenuStore.find("Id",
												result.data[i].Id);
                        if (index != -1) {
                            menuSM.selections.add(MenuStore
													.getAt(index));
                            menuGrid.getView()
													.onRowSelect(index);
                        }
                    }
                }
            }
        });
    });
    ActionPermissionitemGridStore.on("load", function () {
        Ext.Ajax.request({
            url: '/InfraRole/GetActionPermissionsListByRoleId',
            params: {
                'Id': RoleSM.getSelected().get("Id")
            },
            success: function (response, opts) {
                var result = Ext.util.JSON
										.decode(response.responseText);
                if (result.success == false) {
                    JsHelper.ShowError(result.msg);
                } else {
                    var idsData = result.data;
                    var len = idsData.length;
                    for (var i = 0; i < len; i++) {
                        var index = ActionPermissionitemGridStore
												.find("Id", result.data[i].Id);
                        if (index != -1) {
                            ActionPermissionsm.selections
													.add(ActionPermissionitemGridStore
															.getAt(index));
                            ActionPermissionGrid.getView()
													.onRowSelect(index);
                        }
                    }
                }
            }
        });
    });

    

    // 创建框架
    var main = new Ext.Panel({
        border: false,
        layout: 'border',
        items: [grid, PermissionTab]
    });
    // 加载
    JsHelper.ExtTabDoLayout(main);
    // 角色状态Combo Store
    var StateStore = new Ext.data.JsonStore({
        url: '/InfraRole/GetRoleState',
        id: 'Value',
        fields: ['Key', 'Value']
    });

    // 等待状态先加载完
    StateStore.load({
        callback: function (r) {
            filters.addFilter({
                type: 'list',
                dataIndex: 'State',
                options: JsHelper.GetFilterListData(r,
										'Value', 'Key')
            });
            itemGridStore.load({
                params: {
                    start: 0,
                    limit: ALL_PAGESIZE_SETTING
                }
            });
        }
    });

}
Infra_Role();